# Maintainer: Morten Linderud <foxboron@archlinux.org>
# Maintainer: David Runge <dvzrv@archlinux.org>
# Contributor: Bartłomiej Piotrowski <bpiotrowski@archlinux.org>

_name=plugins
pkgname=cni-plugins
pkgver=1.2.0
pkgrel=2
pkgdesc='Some standard networking plugins, maintained by the CNI team'
arch=(loong64 x86_64)
url="https://github.com/containernetworking/plugins"
license=(Apache)
depends=(glibc)
makedepends=(go)
provides=(container-network-stack=1)
# unable to build with LTO: https://github.com/containernetworking/plugins/issues/706
# NOTE: we need /etc/cni/net.d/ for configs
options=(!lto emptydirs)
source=($url/archive/v$pkgver/$_name-v$pkgver.tar.gz)
sha512sums=('fb6fb4f46ac1610b3721f5f3a6ddfb096cbf2e5d5b792306edca5351a3944d2f802170d83e5adec01420395bf64fc8a174ede61ac9b93b5ac6b938a4b48651e6')
b2sums=('6b487a9c9b240c73510f2bc6aaa4a6c79055e43cacca8204781dbc65d231164fed9f3f68a2a0cead7a41a67bfc9d9e4480b488be26415d368da007559a721b25')

prepare() {
  mkdir -vp $_name-$pkgver/bin
}

build() {
  cd $_name-$pkgver

  export CGO_CPPFLAGS="${CPPFLAGS}"
  export CGO_CFLAGS="${CFLAGS}"
  export CGO_CXXFLAGS="${CXXFLAGS}"
  export CGO_LDFLAGS="${LDFLAGS}"
  export GOPATH="${srcdir}"
  export GOFLAGS="-buildmode=pie -mod=readonly -modcacherw"
  go mod edit -replace=golang.org/x/sys=github.com/golang/sys@v0.0.0-20220622161953-175b2fd9d664
  go mod edit -replace=golang.org/x/net=github.com/golang/net@v0.0.0-20220622184535-263ec571b305
  go mod tidy

  # custom go build calls, since build_linux.sh is not flexible enough
  for plugin in plugins/meta/* plugins/main/* plugins/ipam/*; do
    if [[ -d "$plugin"  && "$plugin" != *windows ]]; then
      printf "Building plugin: %s\n" "$(basename $plugin)"
      go build -o bin/ -ldflags "-compressdwarf=false -linkmode external" "./$plugin"
    fi
  done
}

# tests are broken
# check() {
#   cd $_name-$pkgver
#   go test ./...
# }

package() {
  cd $_name-$pkgver
  install -vDm755 bin/* -t "$pkgdir/usr/lib/cni/"
  # strip files manually because makepkg doesn't do it: https://gitlab.archlinux.org/pacman/pacman/-/merge_requests/38
  strip "$pkgdir/usr/lib/cni/"*
  # some applications would build their own versions of CNI plugins in
  # /opt/cni/bin if they are not found (as non-symlink files), so we have to
  # install them twice... ;_;
  install -vDm755 bin/* -t "$pkgdir/opt/cni/bin/"
  install -vdm755 "$pkgdir/etc/cni/net.d/"
  install -vDm644 LICENSE -t "$pkgdir/usr/share/licenses/$pkgname/"
  install -vDm644 plugins/ipam/dhcp/systemd/* -t "$pkgdir/usr/lib/systemd/system/"
}
